"""
/* Copyright 2018 The Enflame Tech Company. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
"""
# !/usr/bin/python
# coding=utf-8

import tensorflow as tf
from tensorflow.python.ops import resource_variable_ops
from utils.flags import InfoDict
from utils.lars_optimizer_enflame import LARSOptimizer
opt_info = InfoDict().opt_info


def get_optimizer(params, learning_rate):
    """Returns the optimizer that should be used based on opt info."""
    if params['optimizer'] == 'momentum':
        opt = tf.train.MomentumOptimizer(
            learning_rate, opt_info['momentum'], use_nesterov=False)
    elif params['optimizer'] == 'sgd':
        opt = tf.train.GradientDescentOptimizer(learning_rate)
    elif params['optimizer'] == 'rmsprop':
        opt = tf.train.RMSPropOptimizer(
            learning_rate,
            opt_info['rmsprop_decay'],
            momentum=opt_info['rmsprop_momentum'],
            epsilon=opt_info['rmsprop_epsilon'])
    elif params['optimizer'] == 'adam':
        if params['use_resource']:
            beta_1 = resource_variable_ops.ResourceVariable(tf.constant(opt_info['adam_beta1']), name='beta1_power',
                                                            collections=[tf.GraphKeys.LOCAL_VARIABLES])
            beta_2 = resource_variable_ops.ResourceVariable(tf.constant(opt_info['adam_beta2']), name='beta2_power',
                                                            collections=[tf.GraphKeys.LOCAL_VARIABLES])
            epsilon_1 = resource_variable_ops.ResourceVariable(tf.constant(opt_info['adam_epsilon']),
                                                               name='adam_epsilon',
                                                               collections=[tf.GraphKeys.LOCAL_VARIABLES])
            opt = tf.train.AdamOptimizer(learning_rate, beta_1,
                                         beta_2, epsilon_1, use_resource=params['use_resource'])
        else:
            opt = tf.train.AdamOptimizer(learning_rate, opt_info['adam_beta1'],
                                         opt_info['adam_beta2'], opt_info['adam_epsilon'])
    elif params['optimizer'] == 'lars':
        opt = LARSOptimizer(learning_rate, momentum=opt_info['momentum'],
                                           weight_decay=params['weight_decay'],
                                           skip_list=['batch_normalization', 'bias', 'BatchNorm', 'preact', 'postnorm'])

    else:
        raise ValueError('Optimizer "{}" was not recognized'.format(params['optimizer']))
    return opt
